<script setup>
import { ref, reactive, onMounted, nextTick } from "vue";
import { chat, getChat, saveChat, deleteChat, clearChat } from "@/api/ai";
import { ChatSquare, Delete } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { v4 as uuidv4 } from "uuid";
import MarkdownIt from 'markdown-it';
import axios from "axios";
import aislogo from "@/assets/icons/svg/aislogo.svg"

defineProps({
  msg: String,
});

//console.log(window.innerWidth);

const svg = `
        <path class="path" d="
          M 30 15
          L 28 17
          M 25.61 25.61
          A 15 15, 0, 0, 1, 15 30
          A 15 15, 0, 1, 1, 27.99 7.5
          L 15 15
        " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
      `;

const messages = ref([]);
const sessionId = ref(uuidv4());

messages.value.push({
  type: "ai",
  msg: "新对话创建成功,很高兴见到你！",
});
const list = ref([]);
const sessionList = ref([]);
const loading = ref(false);
const currentMsg = ref("");
const input = ref("");
const isSmallScreen = ref(false);
onMounted(() => {
  window.addEventListener("resize", handleResize);
  // 组件挂载后立即调用一次 handleResize 以设置初始状态
  handleResize();

});

function handleResize() {

  isSmallScreen.value = window.innerWidth <= 1280;
}

function handleKeyDown(event) {
  if (event.key === "Enter" && !event.shiftKey) {
    event.preventDefault();
    sendQuestion();
  }
}
function sendQuestion() {
  if (currentMsg.value) {
    ElMessage({
      message: "请不要重复提交.",
      type: "error",
      plain: true,
    });
    return;
  }
  if (!input.value) {
    ElMessage({
      message: "请输入要发送的内容.",
      type: "error",
      plain: true,
    });
    return;
  }
  loading.value = true;
  let data = {
    question: input.value,
    session_id: sessionId.value,
  };
  let userMessage = {
    type: "user",
    msg: input.value,
  };
  let tempMessage = {
    type: "temp",
    msg: "",
  };
  const md = new MarkdownIt(); // 初始化 markdown-it 实例

  messages.value.push(userMessage);
  messages.value.push(tempMessage);
  input.value = "";
  axios({
    url: '/api/chat/ai',
    method: 'post',
    headers: {
      'Content-Type': 'application/json',
      // 其他必要的请求头
    },
    data: data
  }).then((res) => {
    messages.value.pop();

    let aiMessage = {
      type: "aiTemp",
      msg: md.render(res.data.output), // 使用 markdown-it 将 AI 的回答渲染为 HTML
      // msg: res.output,
    };

    messages.value.push(aiMessage);

    if (res.data.type == 1) {

      if (res.data.jumpXML.startsWith("http")) {
        window.location.href = `StartFlow://${res.data.jumpXML}`;
      }
    } else if (res.data.type == 2) {
      aiMessage.msg = aiMessage.msg.replaceAll(`<a href="http:`, `<a style='color:blue;' href="http:`)
    }

    loading.value = false;
    loadMsg(aiMessage.msg);
  }).catch(e => {
    messages.value.pop();
    console.log("请求出错", e);
    let aiMessage = {
      type: "ai",
      msg: "AI无法回答,请重新提问",
    };
    messages.value.push(aiMessage);

  })

}

// 新建对话的时候还需要将对话存入数据库
function startNewChat() {
  // 判断是否已经是最新对话
  if (messages.value.length < 2) {
    ElMessage("已经是最新对话");
    return;
  }
  if (currentMsg.value) {
    ElMessage({
      message: "请稍后再创建对话.",
      type: "error",
      plain: true,
    });
    return;
  }
  let data = {
    messages: messages.value,
    session_id: sessionId.value,
  };

  axios({
    url: '/api/chat/ai/save/his',
    method: 'post',
    headers: {
      'Content-Type': 'application/json',
      // 其他必要的请求头
    },
    data: data
  }).then((res) => {
    location.reload();
  })
  // saveChat(data).then((res) => {
  //   location.reload();
  // });
}

async function loadMsg(msg) {
  let totalDelay = 0; // 总延迟时间，初始为0
  const typingSpeed = 10; // 打字速度，单位为毫秒
  const promises = []; // 用于存储所有的 Promise
  for (let char of msg) {
    const promise = new Promise((resolve) => {
      setTimeout(() => {
        currentMsg.value += char;
        resolve(); // 打字完成后解决 Promise
      }, totalDelay);
    });
    promises.push(promise); // 将 Promise 存储到数组中
    totalDelay += typingSpeed;
  }
  await Promise.all(promises);
  messages.value.pop();
  let aiMessage = {
    type: "ai",
    msg: msg,
  };
  messages.value.push(aiMessage);
  currentMsg.value = "";


  nextTick(() => {
    // 获取插入的 HTML 元素
    handleTagA();
  })

}

// 处理所有a标签的点击事件
const handleTagA = (event) => {
  const elements = document.querySelectorAll('a')
  if (elements.length > 0) {
    elements.forEach(element => {
      let hrefValue = element.getAttribute('href')
      if (hrefValue) {
        element.removeAttribute('onclick');
        element.addEventListener('click', handleAAA);
        // const hasFuncType = hrefValue.includes('funcType');
        // if (hasFuncType) {
        //   element.removeAttribute('onclick');
        //   element.addEventListener('click', handleAAA);
        // } else {
        //   element.setAttribute('target', '_blank')
        // }
      }
    });
  };
};

// 定义点击事件处理函数
const handleAAA = (event) => {
  event.preventDefault();
  const target = event.target;
  const hrefValue = target.getAttribute('href');
  console.log('创建按钮被点击了');
  console.log('href 属性的值为:', hrefValue);
  window.location.href = `StartFlow://${hrefValue}`;
};

// // 定义点击事件处理函数
// const handleAAA = (event) => {
//   event.preventDefault();
//   const target = event.target;
//   const hrefValue = target.getAttribute('href');
//   console.log('创建按钮被点击了');
//   console.log('href 属性的值为:', hrefValue);
//   axios.get(hrefValue)
//     .then(response => {
//       console.log(response.data);

//       let aiMessage = {
//         type: "aiTemp",
//         msg: response.data, // 使用 markdown-it 将 AI 的回答渲染为 HTML
//         // msg: res.output,
//       };
//       messages.value.push(aiMessage);


//       loadMsg(response.data)
//     })
//     .catch(error => {
//       console.error(error);
//     });
// };


function trimmedText(text) {
  // 如果文本长度大于5，则截取前5个字符并添加省略号
  if (text && text.length > 12) {
    return text.slice(0, 12) + "...";
  }
  return text;
}
//
function goChatHis(item, index) {
  messages.value = item;
  sessionId.value = sessionList.value[index];
}
function init() {
  list.value = [];
  sessionList.value = [];
  // 获取chat的记录

  axios({
    url: '/api/chat/ai/his',
    method: 'post',
    headers: {
      'Content-Type': 'application/json',
      // 其他必要的请求头
    }
  }).then((res) => {
    if (res) {
      res.data.forEach((e) => {
        list.value.push(JSON.parse(e.messages));
        sessionList.value.push(e.session_id);
      });
    }
    //list.value = res;
    //console.log(list.value);
  })

  // getChat().then((res) => {
  //   if (res) {
  //     res.forEach((e) => {
  //       list.value.push(JSON.parse(e.messages));
  //       sessionList.value.push(e.session_id);
  //     });
  //   }
  //   //list.value = res;
  //   //console.log(list.value);
  // });
}
function deleteMyChat(i) {
  ElMessageBox.confirm("确认删除该条对话吗?", "删除确认", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      let data = {
        session_id: sessionList.value[i],
      };

      axios({
        url: '/api/chat/ai/delete',
        method: 'post',
        headers: {
          'Content-Type': 'application/json',
          // 其他必要的请求头
        },
        data: data
      }).then((res) => {
        ElMessage({
          type: "success",
          message: res.data.message,
        });

        // init();
      })

      // deleteChat(data).then((res) => {
      //   ElMessage({
      //     type: "success",
      //     message: res.message,
      //   });

      //   init();
      // });
    })
    .catch(() => { });
}

function clearAllChat() {
  ElMessageBox.confirm("确认清空对话吗?", "清空确认", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {

      axios({
        url: '/api/chat/ai/clear',
        method: 'post',
        headers: {
          'Content-Type': 'application/json',
          // 其他必要的请求头
        }
      }).then((res) => {
        location.reload();
      })

      // clearChat().then((res) => {
      //   location.reload();
      // });
    })
    .catch(() => { });
}
// init();
</script>

<template>
  <div class="body-div">

    <!-- // 加了91高度 -->
    <el-card style="height: 100vh; background-color: #e9ebf0" body-style="padding:5px">
      <el-row :gutter="10">
        <el-col :span="4" v-if="false">

          <div v-if="isSmallScreen"
            style="display: flex; flex-direction: column; justify-content: center; align-items: center; ">
            <el-button @click="startNewChat" color="#626aef" :dark="false" :icon="ChatSquare" plain type="default"
              style="border-radius: 5px; width: 100%; position: relative; font-size: 16px;">新建对话</el-button>
            <!-- <el-button @click="clearAllChat" size="small" type="danger" :dark="false" :icon="Delete" plain
              style="border-radius: 5px;width: 100px;margin-top:5px">清空对话</el-button> -->
          </div>
          <div v-else>
            <el-button @click="startNewChat" color="#626aef" :dark="false" :icon="ChatSquare" plain
              style="border-radius: 6px; width: 100%; position: relative; font-size: 14px;"
              type="default">新建对话</el-button>
            <!-- <el-button @click="clearAllChat" type="danger" :dark="false" :icon="Delete" plain
              style="border-radius: 6px;width: 100px;margin-left:10px">清空对话</el-button> -->
          </div>

          <el-divider style="margin: 10px 0 ;" />
          <h4 style="margin: 0; font-size: 18px; font-weight: bold; margin-bottom: 10px;">对话记录</h4>
          <!-- <el-card v-for="i in 100" style="" class="hisChat">  -->
          <!-- <div style="overflow-y: auto;max-height: 70vh;"> -->
          <div style="height: calc(100vh - 190px)">
            <el-scrollbar>
              <div v-for="(item, i) in list" :key="i" class="hisChat" @click="goChatHis(item, i)">
                <span>{{ trimmedText(item[1].msg) }}</span>

                <Delete class="deleteIcon" @click.stop="deleteMyChat(i)" />
              </div>
            </el-scrollbar>
          </div>

        </el-col>
        <el-col :span="24">
          <div style="background-color: #f5f6f8; border-radius: 10px;">
            <el-scrollbar style="height: calc(100vh - 70px);padding-right:10px">
              <div v-for="m in messages" :key="m">
                <div v-if="m.type == 'temp'" v-loading="loading" :element-loading-svg="svg" class="aiMsg"
                  element-loading-svg-view-box="-10, -10, 50, 50">
                  <span v-for="(char, index) in loadMsg" :key="index">{{
                    char
                  }}</span>
                </div>

                <div v-if="m.type == 'ai'" class="aiMsg">
                  <div>
                    <img :src="aislogo" class="logo" alt="Vite logo" />
                  </div>
                  <div class="space-10">
                    <!-- {{ m.msg }} -->
                    <span v-html="m.msg"></span>
                  </div>
                </div>
                <div v-if="m.type == 'aiTemp'" class="aiMsg">
                  <div>
                    <img :src="aislogo" class="logo" alt="Vite logo" />
                  </div>
                  <div class="space-10">
                    <span v-html="currentMsg"></span>
                  </div>
                </div>
                <div v-if="m.type == 'user'" class="userMsg">
                  {{ m.msg }}
                </div>
              </div>
            </el-scrollbar>


            <div style="display: flex; justify-content: center; align-items: center; ">
              <div class="user-input">
                <input v-model.trim="input" type="text" placeholder="和机器人聊天" @keydown="handleKeyDown">
                <el-button @click="sendQuestion" size="small" type="primary" style="padding: 5px;">
                  <el-icon>
                    <CaretRight size='23' />
                  </el-icon>
                </el-button>
              </div>
            </div>
          </div>

        </el-col>
      </el-row>
    </el-card>

  </div>
</template>

<style scoped>
.aiMsg {
  float: left;
  background-color: #ffffff;
  border-top-left-radius: 10px;
  /* 设置左上角弧度为10px */
  border-bottom-left-radius: 0;
  /* 设置左下角弧度为10px */
  border-top-right-radius: 10px;
  /* 设置右上角弧度为10px */
  border-bottom-right-radius: 10px;
  /* 设置右下角弧度为0，即保持直角 */
  padding-top: 6px;
  padding-bottom: 1px;
  padding-left: 10px;
  padding-right: 10px;
  margin: 5px;
  clear: both;
  display: flex;
  text-align: left;
  /* 添加这行，清除左右浮动，强制换行 */

  font-size: 14px;
}

.userMsg {
  float: right;
  background-color: #e0dfff;
  border-top-left-radius: 10px;
  /* 设置左上角弧度为10px */
  border-bottom-left-radius: 10px;
  /* 设置左下角弧度为10px */
  border-top-right-radius: 10px;
  /* 设置右上角弧度为10px */
  border-bottom-right-radius: 0;
  /* 设置右下角弧度为0，即保持直角 */
  padding-top: 6px;
  padding-bottom: 6px;
  padding-left: 10px;
  padding-right: 10px;
  margin: 5px;
  clear: both;
  /* 添加这行，清除左右浮动，强制换行 */

  font-size: 15px;
}

.space-10 {
  margin-left: 10px;
  margin-top: 4px;
}

.container {
  display: flex;
}

.hisChat {
  height: 10px;
  border-radius: 12px;
  line-height: 10px;
  text-align: left;
  padding: 10px;
  width: 90%;

  font-size: 16PX;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.hisChat:hover {
  background-color: #dddaf7;
  color: #626aef;
  cursor: pointer;
}

.deleteIcon {
  display: none;
  width: 1em;
  height: 1em;
  color: #f56c6c;
  float: right;
  /* margin-top: 2px; */
}

.hisChat:hover .deleteIcon {
  display: inline-block;
}

.el-button:focus {
  outline: none;
  /* 移除轮廓线 */
  box-shadow: none;
  /* 移除阴影效果 */
}

.el-card__body {
  padding: 0;
}

.el-button+.el-button {
  margin-left: 0;
}

.body-div {
  font-size: 12px;
}

.logo {
  width: 24px;
  height: 24px
}

::v-deep(.el-input__inner) {
  height: 20px;
  /* 修改为你想要的高度 */
  line-height: 20px;
  /* 保持文本垂直居中 */
  font-size: 12px;
}

.submitBtn {
  font-size: 12px;
  display: flex;
}

::v-deep(.submitBtn span) {
  font-size: 12px;
  line-height: 1px;
}

::v-deep(el-divider el-divider--horizontal) {
  margin: 0;
}

::v-deep(p) {
  margin-top: 0;
}

.user-input {
  width: 100%;
  display: flex;
  align-items: center;
  border: 1px solid #ccc;
  border-radius: 10px;
  padding: 0 10px;
  background-color: white;
  /* margin-bottom: 10px; */
}

.user-input input {
  flex: 1;
  border: none;
  outline: none;
  font-size: 16px;
  padding: 10px 0;
}
</style>
